package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    // 获取微信官方提供的openid的请求地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 调用获取openid的方法
        String openid = getOpenid(userLoginDTO.getCode());
        // 如果openId数据为空,则提示前端请求失败
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 如果openId数据不为空，则调用mapper层的方法查询数据库中是否有对应用户
        User user = userMapper.getByOpenId(openid);
        // 如果未查询到，则表示当前用户是新用户
        if (user == null) {
            // 封装一个entity层用户对象
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            // 调用mapper层的方法
            userMapper.insert(user);
        }
        // 返回封装好的用户对象
        return user;
    }

    /**
     * 调用微信微信提供的API获取openid
     */
    private String getOpenid(String code) {
        // 创建请求参数对象容器
        Map<String, String> requestPayload = new HashMap<>();
        // 准备请求参数
        requestPayload.put("appid", weChatProperties.getAppid());
        requestPayload.put("secret", weChatProperties.getSecret());
        requestPayload.put("js_code", code);
        requestPayload.put("grant_type", weChatProperties.getGrantType());
        // 调用HttpClientUtil工具类上的方法发送请求并获取json格式的响应数据
        String resJson = HttpClientUtil.doGet(WX_LOGIN, requestPayload);
        // 解析json格式的响应数据
        JSONObject res = JSON.parseObject(resJson);
        // 获取响应数据中的openid数据
        String openid = res.getString("openid");
        return openid;
    }
}
